package com.example.demo.service.impl;

import com.example.demo.common.convention.exception.ClientException;
import com.example.demo.common.convention.result.Result;
import com.example.demo.dao.entity.QRCode;
import com.example.demo.service.QRCodeService;
import com.example.demo.service.ScriptService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.example.demo.common.convention.errorcode.BaseErrorCode.*;

/**
 * QRCodeServiceImpl 是一个用于处理二维码生成和确认的服务类，
 * 它继承自 ServiceImpl，并实现了 QRCodeService 接口。
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class QRCodeServiceImpl  implements QRCodeService {


    private final ScriptService scriptService;//运行脚本
    private final Map<String, QRCode> QRCodeStorage = new ConcurrentHashMap<>();


    @Override
    public DeferredResult<Object> getQRCode(String userId) {
        DeferredResult<Object> deferredResult = new DeferredResult<>((long) 70000); // 超时时间设置为70秒
        QRCode qrCode= new QRCode();
        QRCodeStorage.put(userId,qrCode);
        //启动脚本 proxy
//        Proxy proxy = new Proxy();
//        //String url = "socks5://account:pwd|192.168.1.100:1080";
//        proxy.setProxyIp("socks5://qwe123456:qwe123456|113.133.161.157:2555");
//
//        log.info(scriptService.runLogin(proxy.getProxyIp(),"location"));
        //log.info(scriptService.runLogin("localhost", "location"));
        //scriptService.runLocation();
        // 处理长轮询
        new Thread(() -> {
            String qrCodeString;
            synchronized (qrCode){
                while (qrCode.getNewQrcode() == null || !qrCode.getNewQrcode()){
                    try {
                        qrCode.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                qrCodeString = qrCode.getCode();
                QRCodeStorage.remove(userId);
            }
            Map<String,Object> map = new HashMap<>();

            map.put("qrCodeString",qrCodeString);
            Result<Map<String,Object>> result = new Result<Map<String,Object>>()
                    .setCode("0")
                    .setData(map)
                    .setMessage("请求成功");
            deferredResult.setResult(result);
        }).start();

        // 处理超时
        deferredResult.onTimeout(() -> {
            Result<String> result = new Result<String>()
                    .setCode("1")
                    .setMessage("请求超时");
            deferredResult.setResult(result);
        });

        return deferredResult;
    }
    @Override
    public String postQrCode( String userId,  String code) {
        QRCode qrCode = QRCodeStorage.get(userId);
        if (qrCode != null) {
            synchronized (qrCode) {  // 保持同步以确保线程安全
                if (qrCode.getNewQrcode()==null||!qrCode.getNewQrcode()) {
                    qrCode.setCode(code);
                    qrCode.setNewQrcode(true);
                    qrCode.notify();
                } else {
                    throw new ClientException(QRCODE_USED_ERROR);
                }
            }
        } else {
            throw new ClientException(QRCODE_USER_NULL_ERROR);
        }
        return userId;
    }



}
